package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisTemplateConfig {
    @Autowired
    public RedisTemplateConfig(RedisTemplate redisTemplate) {
        // 创建jackjson的序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 允许访问任何属性
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 转换json时，将对象全类名一起保存下来。以便于反序列化时，可以找到对应的类
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 设置redisTemplate的 key 序列化方式为 string
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置redisTemplate的 value 序列化方式为 jackjson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        // 设置hash类型的key序列化方式为jackjson
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        // 工厂模式创建的redisTemplate对象，需要调用afterPropertiesSet方法，才能使上面的配置生效
        redisTemplate.afterPropertiesSet();
    }

    ;
}
